import { getAllRoleList } from '@/apis/accessManagement/role'
import { getAvailableMenu } from '@/apis/accessManagement/menu'
import { getUserMenu } from '@/apis/accessManagement/menu'
import { editRole } from '@/apis/accessManagement/role'
import { addRole } from '@/apis/accessManagement/role'
import { switchForbidden } from '@/apis/accessManagement/role'
import { deleteRole } from '@/apis/accessManagement/role'
import { permitRole } from '@/apis/accessManagement/role'
import { editUserRole } from '@/apis/accessManagement/role'

import { getIpList, getIpInfo, updateIpInfo, delIp, addIp } from '@/apis/accessManagement/ip'
import ExcelTable from '@/components/exportExcel'
import { ActionType, ProFormInstance } from '@ant-design/pro-components'
import { Button, Drawer, Modal, Form, Input, Flex, Tree, message, Switch, Spin } from 'antd'
import { useRef, useState, useEffect } from 'react'
import type { TreeProps } from 'antd'
import routerId from '@config/routes/routerId'
import { storeGlobalUser } from '@/store/globalUser'
import { observer } from 'mobx-react'
const ipManage: React.FC = () => {
  const { authMenuPaths } = storeGlobalUser
  useRef<ActionType>()
  useRef<ProFormInstance>()
  const [tableItem, setTableItem] = useState()
  const [form] = Form.useForm()
  const actionRef: any = useRef()
  const [messageApi, contextHolder] = message.useMessage()
  const [loading, setLoading] = useState(false)
  const [id, setId] = useState(null)
  const [drawerMode, setDrawerMode] = useState(null)

  const [authorizationDrawer, setAuthorizationDrawer] = useState(false)
  const [addDrawer, setAddDrawer] = useState(false)
  const [titleDrawer, setTitleDrawer] = useState('新增')

  const delIpAuth = authMenuPaths[routerId.delIp]
  const updateIpAuth = authMenuPaths[routerId.updateIp]
  const addIpAuth = authMenuPaths[routerId.addIp]

  function showAddEditDrawer(title: string, item: any, mode: any) {
    setTitleDrawer(title)
    setAddDrawer(true)
    if (mode === 2) {
      setId(item.id)
      form.setFieldsValue({ ip: item.ip })
      form.setFieldsValue({ desc: item.desc })
    }
    setDrawerMode(mode)
    // console.log(item)
    // setTableItem(item)
  }

  function onCloseDrawer() {
    form.resetFields()
    setAddDrawer(false)
    setAuthorizationDrawer(false)
  }

  // 提交修改
  const subUpdate = async () => {
    // setLoading(true)
    try {
      const response = await updateIpInfo({
        ip: form.getFieldValue('ip'),
        desc: form.getFieldValue('desc'),
        id: id
      })
      if (response || response.data) {
        if (response?.errCode === 0) {
          message.success('ip修改成功')
          form.resetFields()
          setAddDrawer(false)
          actionRef.current?.reloadAndRest()
        } else {
          message.error(`提交失败: ${response?.errMsg || '未知错误'}`)
        }
      } else {
        message.error('响应数据格式错误')
      }
    } catch (error) {
      console.error('Error:', error)
    } finally {
      // setLoading(false)
    }
  }

  // 提交新增角色
  const subAdd = async () => {
    try {
      const response = await addIp({
        ip: form.getFieldValue('ip'),
        desc: form.getFieldValue('desc')
      })
      if (response || response.data) {
        if (response?.errCode === 0) {
          message.success('ip添加成功')
          form.resetFields()
          setAddDrawer(false)
          actionRef.current?.reloadAndRest()
        } else {
          message.error(`提交失败: ${response?.errMsg || '未知错误'}`)
        }
      } else {
        message.error('响应数据格式错误')
      }
    } catch (error) {
      console.error('Error:', error)
    } finally {
    }
  }

  // 删除ip
  const subDelete = async (record: any) => {
    setLoading(true)
    try {
      const response = await delIp({
        id: record.id
      })
      if (response || response.data) {
        if (response?.errCode === 0) {
          message.success('删除成功')
          actionRef.current?.reloadAndRest()
        } else {
          message.error(`提交数据失败: ${response?.errMsg || '未知错误'}`)
        }
      } else {
        message.error('响应数据格式错误')
      }
    } catch (error) {
      console.error('Error:', error)
    } finally {
      setLoading(false)
    }
  }

  return (
    <>
      {contextHolder}
      <Spin spinning={loading} fullscreen size="large" />
      <ExcelTable
        actionRef={actionRef}
        requestFn={async params => {
          const {
            pageNum,
            pageSize,
            roleName = '',
            roleCode,
            status = 0,
            startTime = '',
            endTime = '',
            ...newParams
          } = params // 处理所需参数名
          const data = await getIpList({
            ...newParams,
            pagination: { pageNumber: pageNum, showNumber: pageSize },
            roleName: roleName,
            roleCode: roleCode,
            status: parseInt(status),
            startTime: startTime,
            endTime: endTime
          })
          return data
        }}
        rowSelection={false}
        toolBarRenderFn={() => [
          addIpAuth && (
            <Button key="add" onClick={() => showAddEditDrawer('新增', {}, 1)}>
              新增
            </Button>
          )
        ]}
        columns={[
          //   {
          //     title: 'id',
          //     dataIndex: 'id'
          //   },
          {
            title: 'ip地址',
            dataIndex: 'ip'
            // valueType: 'select',
            // valueEnum: {
            //   0: '全部',
            //   1: '正常',
            //   2: '禁用'
            // }
          },
          /** table */
          {
            title: '描述',
            dataIndex: 'desc',
            hideInSearch: true
          },
          {
            title: '更新时间',
            dataIndex: 'updateTime',
            valueType: 'dateTime',
            hideInSearch: true
          },
          {
            title: '操作',
            key: 'option',
            valueType: 'option',
            render: (_, record) => [
              updateIpAuth && (
                <a key="update" onClick={() => showAddEditDrawer('修改ip地址', record, 2)}>
                  修改
                </a>
              ),
              delIpAuth && (
                <a
                  key="delete"
                  onClick={() => {
                    Modal.warning({
                      title: '提示',
                      content: '确定删除该ip吗?',
                      okText: '确定',
                      okCancel: true,
                      onOk() {
                        subDelete(record)
                      }
                    })
                  }}
                >
                  删除
                </a>
              )
            ]
          }
        ]}
      />
      <Drawer title={titleDrawer} onClose={onCloseDrawer} open={addDrawer}>
        <Form form={form} onFinish={drawerMode === 1 ? subAdd : subUpdate}>
          <Form.Item label="ip地址" name="ip" rules={[{ required: true, message: '请输入ip地址' }]}>
            <Input placeholder="请输入ip地址" maxLength={50} />
          </Form.Item>
          <Form.Item label="ip描述" name="desc" rules={[{ required: true, message: '请输入描述' }]}>
            <Input.TextArea
              rows={4}
              maxLength={200}
              placeholder="请输入您的ip描述，最多不超过200字。"
            />
          </Form.Item>
          <Form.Item>
            <Flex justify="center" align="center">
              <Button type="primary" htmlType="submit">
                提交
              </Button>
              <Button style={{ marginLeft: 10 }} onClick={onCloseDrawer}>
                返回
              </Button>
            </Flex>
          </Form.Item>
        </Form>
      </Drawer>
    </>
  )
}

export default observer(ipManage)
